local skynet = require "skynet"
local socket = require "socket"

local index = 1
local d_index = 1
local l_host
local l_from
local l_on = 0

--[[
sprintf(buff, "1:%0.8x%0.8x%0.8x:%u:%u:%0.2d:%0.2d", CpuID[0],CpuID[1],CpuID[2],sendIndex,RecvIndex,switch1,switch2);
1:


--]]
function string_split(s)  
    local fields = {}  
    local pattern = "([^:]+)"  
    local index = 1
    string.gsub(s, pattern, function (c) 
                            fields[index] = c 
                            index = index + 1
                            end)  
    return fields
end  

function recv_data(s)
	local field = string_split(s)
	skynet.error("fileld:",field[1],field[2],field[3],field[4])
	if tonumber(field[1]) == 1 then
		return "1:"..tostring(field[3])
	elseif tonumber(field[1]) == 2 then
		if tonumber(field[4]) ~= (d_index-1) then
			skynet.error("fail: recv_data not send_index:"..field[4].." :cu send index:"..d_index)
            return nil
		end
        skynet.error("succeed:recv send data index = "..tonumber(field[4]))
	end
	skynet.error("fail: recv data: return nil")
	return nil
end

local function time_on()
    while(true) do
        if l_host and l_from then
        	local str = string.format("2:%d:%d:%d",d_index,1,1,3000)
        	if l_on == 0 then
        		str = string.format("2:%d:%d:%d",d_index,1,0,3000)
        		l_on = 1
        	else
        		l_on = 0
        	end
            d_index = d_index + 1
		    socket.sendto(l_host, l_from, str)
          
        end
        skynet.sleep(30*60*100)
        --skynet.sleep(5*100)
    end
end

local function server()
	l_host = socket.udp(function(str, from)
		skynet.error("server recv:"..str.."    addr="..socket.udp_address(from))

        l_from = from
        local ret = recv_data(str)
        if ret then
		    socket.sendto(l_host, from, ret)
	    end

        index = index + 1
	end , "0.0.0.0", 8765)	-- bind an address
end

skynet.start(function()
	skynet.fork(server)
	skynet.fork(time_on)
end)
